/**
 *  直接传递到阿里云上：在h5上支持分片传递，小程序不支持
 */
import {
	guid
} from '@/utils/index';
import MaterialApi from '@/api/user/material';

export default {
	props: {
		folder: {
			type: Object,
			default: () => {}
		},
		scene: {
			type: String,
			default: "Document"
		}
	},
	data() {
		return {
			showProgress: false, // 进度条
			files: [],
			options: {
				count: 9, //默认9
				sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
				sourceType: ['album', 'camera'], //从相册选择
				compressed: false, //是否压缩所选的视频源文件，默认值为 true，需要压缩。
				maxDuration: 60 * 60, //拍摄视频最长拍摄时间，单位秒。最长支持 60 * 60 秒。
				camera: 'back', //'front'、'back'，默认'back'
				extension: undefined, // 扩展名
			}
		}
	},
	methods: {

		// 通过
		path2Name: function(path) {
			if (/([^\\/]+\.[^\\/]+)/i.test(path)) {
				return RegExp.$1;
			}
			return path;
		},

		// 选择图片
		chooseImage: function(config) {
			let self = this;
			let options = Object.assign({}, config || {}, this.options)
			return new Promise((resolve, reject) => {
				uni.chooseImage({
					count: options.count,
					sizeType: options.sizeType,
					sourceType: options.sourceType,
					extension: options.extension,
					success: function(res) {
						for (var i = 0; i < res.tempFiles.length; i++) {
							res.tempFiles[i].fileType = "image"
							if (!res.tempFiles[i].name) {
								res.tempFiles[i].name = self.path2Name(res.tempFiles[i].path);
							}
						}
						resolve(res.tempFiles);
					},
					fail: err => {
						reject({
							errMsg: err.errMsg,
							errCode: err.errCode,
							statusCode: 0,
						});
					}
				});
			});
		},

		// 选择视频
		chooseVideo: function(config) {
			let options = Object.assign({}, config || {}, this.options)
			return new Promise((resolve, reject) => {
				let self = this;
				uni.chooseVideo({
					sourceType: options.sourceType,
					compressed: options.compressed,
					maxDuration: options.maxDuration,
					extension: options.extension,
					camera: options.camera,
					success: function(res) {
						let files = [{
							path: res.tempFilePath,
							fileType: "video"
						}];
						// #ifdef APP-PLUS || H5 || MP-WEIXIN
						files[0].duration = res.duration;
						files[0].size = res.size;
						files[0].height = res.height;
						files[0].width = res.width;
						// #endif
						files[0].name = res.name ? res.name : self.path2Name(res.tempFilePath);
						resolve(files);
					},
					fail: err => {
						reject({
							errMsg: err.errMsg,
							errCode: err.errCode,
							statusCode: 0,
						});
					}
				});
			});
		},

		// 选择图片或视频
		chooseFile: function(config) {
			let options = Object.assign({}, config || {}, this.options)
			return new Promise((resolve, reject) => {
				let self = this;
				// #ifdef MP-WEIXIN
				console.log("小程序上传文件")
				this._chooseFileWxmp(options, resolve, reject);
				// #endif
				// #ifdef H5
				console.log("H5上传文件")
				this._chooseFileH5(options, resolve, reject);
				// #endif
				//#ifndef H5 || MP-WEIXIN
				reject("暂不支持！")
				// #endif
			});
		},

		// h5 是使用的选择文件
		_chooseFileH5: function(options, resolve, reject) {
			uni.chooseFile({
				type: 'all',
				extension: options.extension,
				success: function(res) {
					for (var i = 0; i < res.tempFiles.length; i++) {
						res.tempFiles[i].fileType = "file"
						if (!res.tempFiles[i].name) {
							res.tempFiles[i].name = self.path2Name(res.tempFiles[i].path);
						}
					}
					resolve(res.tempFiles);
				},
				fail: err => {
					reject({
						errMsg: err.errMsg,
						errCode: err.errCode,
						statusCode: 0,
					});
				}
			});
		},

		// 微信小程序
		_chooseFileWxmp: function(options, resolve, reject) {
			wx.chooseMessageFile({
				type: 'all',
				extension: options.extension,
				success: function(res) {
					for (var i = 0; i < res.tempFiles.length; i++) {
						res.tempFiles[i].fileType = "file"
						if (!res.tempFiles[i].name) {
							res.tempFiles[i].name = self.path2Name(res.tempFiles[i].path);
						}
					}
					resolve(res.tempFiles);
				},
				fail: err => {
					reject({
						errMsg: err.errMsg,
						errCode: err.errCode,
						statusCode: 0,
					});
				}
			});
		},

		// 上传文件
		uploadFile: function(file, param) {
			let self = this;
			return new Promise((resolve, reject) => {
				let uploadTask = uni.uploadFile({
					url: param.host,
					filePath: file.file.path,
					name: 'file',
					formData: {
						'name': param.name,
						'key': param.key,
						'policy': param.policy,
						'OSSAccessKeyId': param.accessid,
						'signature': param.signature,
						'success_action_status': '200',
					},
					success: function(res) {
						if (res.statusCode != 200) {
							reject(new Error('上传错误:' + JSON.stringify(res)))
							return;
						}
						resolve();
					},
					fail: function(err) {
						reject(err);
					},
				});

				// 监听文件上传进度
				file.uploadTask = uploadTask
				uploadTask.onProgressUpdate(async function(res) {
					self.$set(file, 'progress', res.progress)
					file.uploadInfo = res
				});
			});
		},

		// 结束上传
		finishUpload: function(file, resource) {
			return new Promise((resolve) => {
				setTimeout(() => {
					try {
						let index = this.files.findIndex(f => f.id === file.id);
						this.files.splice(index, 1)
						// this.$emit("upload:file", resource);
						this.emitUploadFile(resource);
						if (!this.files.length) {
							this.showProgress = false;
							// this.$emit("upload:end", true);
							this.emitUploadFinish();
						}
					} finally {
						resolve();
					}
				}, 2000);
			});
		},

		// 文件上传结束
		emitUploadFile: function(resource) {
			this.$emit("upload:file", resource);
		},

		// 所有上传结束
		emitUploadFinish: function() {
			this.$emit("upload:end", true);
		},

		// 上传图片
		uploadImages: async function(options = {}) {
			try {
				let files = await this.chooseImage(options);
				files.forEach(file => {
					this.__doUpload(options, file);
				})
			} catch (err) {
				console.log(err)
				options.onUploadError && options.onUploadError(err);
			}
		},

		// 上传视频
		uploadVideos: async function(options = {}) {
			try {
				let files = await this.chooseVideo(options);
				files.forEach(file => {
					this.__doUpload(options, file);
				})
			} catch (err) {
				console.log(err)
				options.onUploadError && options.onUploadError(err);
			}
		},

		// 上传文件
		uploadFiles: async function(options = {}) {
			try {
				let files = await this.chooseFile(options);
				files.forEach(file => {
					this.__doUpload(options, file);
				})
			} catch (err) {
				console.log(err)
				options.onUploadError && options.onUploadError(err);
			}
		},

		// 执行上传: 并发的上传
		__doUpload: function(options, file) {
			this.doUpload(options, {
				id: guid(),
				index: this.files.length,
				name: file.name,
				size: file.size,
				file: file,
				progress: 0,
				status: 0,
			});
		},

		// 执行上传
		doUpload: async function(options, file) {
			this.showProgress = true;
			this.files.push(file);

			console.log('#########上传文件#########')
			console.log(file)

			// 换取签名
			let res = await MaterialApi.prepare({
				name: file.name,
				size: file.size,
				parentId: this.folder ? this.folder.id : ''
			}, this.scene);

			// 上传的参数
			let param = res.obj;

			console.log(param)
			// 上传文件
			try {
				await this.uploadFile(file, param);
				this.$set(file, 'progress', 100);
				this.$set(file, 'status', 1); // 成功
				console.log("上传成功")
			} catch (e) {
				this.$set(file, 'status', 3); // 失败
				console.log("上传失败：")
				console.log(e)
			}

			// 对外暴露的数据
			let resource = {
				id: param.materialId,
				name: file.name,
				status: file.status,
				content: JSON.stringify(param.store)
			}

			// 修改上传的数据
			await MaterialApi.confirm(resource)

			// 删除结束的文件
			await this.finishUpload(file, resource);
			console.log('#########################')
		},
	},
}